<template>
  <div class="accounting-entry">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="header-title">会计分录管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="addEntry">
              <el-icon><Plus /></el-icon>
              新增分录
            </el-button>
            <el-button @click="autoGenerateEntries">
              <el-icon><MagicStick /></el-icon>
              自动生成
            </el-button>
          </div>
        </div>
      </template>

      <!-- 分录列表 -->
      <el-table :data="entries" stripe border v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="accountCode" label="科目编码" width="120" />
        <el-table-column prop="accountName" label="科目名称" min-width="150" />
        <el-table-column prop="debitAmount" label="借方金额" width="120" align="right">
          <template #default="scope">
            <span v-if="scope.row.debitAmount > 0" class="debit-amount">
              ¥{{ scope.row.debitAmount.toLocaleString() }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="creditAmount" label="贷方金额" width="120" align="right">
          <template #default="scope">
            <span v-if="scope.row.creditAmount > 0" class="credit-amount">
              ¥{{ scope.row.creditAmount.toLocaleString() }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="summary" label="摘要" min-width="200" />
        <el-table-column prop="auxiliary" label="辅助核算" width="120" />
        <el-table-column :label="t('common.actions')" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editEntry(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteEntry(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 借贷平衡检查 -->
      <div class="balance-check">
        <el-alert
          :title="balanceStatus.title"
          :type="balanceStatus.type"
          :description="balanceStatus.description"
          show-icon
          :closable="false"
        />
      </div>
    </el-card>

    <!-- 分录编辑弹窗 -->
    <el-dialog 
      v-model="entryDialog.visible" 
      :title="entryDialog.isEdit ? '编辑分录' : '新增分录'"
      width="60%"
      @close="closeEntryDialog"
    >
      <el-form :model="entryDialog.form" :rules="entryRules" ref="entryFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="科目编码" prop="accountCode">
              <el-select 
                v-model="entryDialog.form.accountCode" 
                placeholder="请选择科目"
                filterable
                @change="onAccountChange"
              >
                <el-option 
                  v-for="account in accountSubjects" 
                  :key="account.code" 
                  :label="`${account.code} - ${account.name}`" 
                  :value="account.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科目名称" prop="accountName">
              <el-input v-model="entryDialog.form.accountName" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="借方金额" prop="debitAmount">
              <el-input-number 
                v-model="entryDialog.form.debitAmount" 
                :min="0" 
                :precision="2" 
                style="width: 100%"
                placeholder="请输入借方金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷方金额" prop="creditAmount">
              <el-input-number 
                v-model="entryDialog.form.creditAmount" 
                :min="0" 
                :precision="2" 
                style="width: 100%"
                placeholder="请输入贷方金额"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="辅助核算" prop="auxiliary">
              <el-select v-model="entryDialog.form.auxiliary" placeholder="请选择辅助核算" clearable>
                <el-option label="客户" value="customer" />
                <el-option label="供应商" value="supplier" />
                <el-option label="部门" value="department" />
                <el-option label="项目" value="project" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="辅助核算值" prop="auxiliaryValue">
              <el-input v-model="entryDialog.form.auxiliaryValue" placeholder="请输入辅助核算值" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="摘要" prop="summary">
          <el-input 
            v-model="entryDialog.form.summary" 
            type="textarea" 
            :rows="3"
            placeholder="请输入分录摘要"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEntryDialog">取消</el-button>
          <el-button type="primary" @click="saveEntry">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus, MagicStick, Edit, Delete } from '@element-plus/icons-vue'

// 国际化相关
const t = (key: string) => key

// 响应式数据
const loading = ref(false)
const entryFormRef = ref<FormInstance>()

// 分录数据
const entries = ref([
  {
    id: 1,
    accountCode: '1001',
    accountName: '库存现金',
    debitAmount: 0,
    creditAmount: 15000,
    summary: '收到商品销售收入',
    auxiliary: 'customer',
    auxiliaryValue: '田中太郎'
  },
  {
    id: 2,
    accountCode: '6001',
    accountName: '主营业务收入',
    debitAmount: 0,
    creditAmount: 15000,
    summary: '商品销售收入',
    auxiliary: 'customer',
    auxiliaryValue: '田中太郎'
  }
])

// 分录弹窗
const entryDialog = reactive({
  visible: false,
  isEdit: false,
  form: {
    id: '',
    accountCode: '',
    accountName: '',
    debitAmount: 0,
    creditAmount: 0,
    summary: '',
    auxiliary: '',
    auxiliaryValue: ''
  }
})

// 科目数据
const accountSubjects = ref([
  { code: '1001', name: '库存现金', type: 'asset' },
  { code: '1002', name: '银行存款', type: 'asset' },
  { code: '1012', name: '其他货币资金', type: 'asset' },
  { code: '1101', name: '短期投资', type: 'asset' },
  { code: '1121', name: '应收票据', type: 'asset' },
  { code: '1122', name: '应收账款', type: 'asset' },
  { code: '1123', name: '预付账款', type: 'asset' },
  { code: '1131', name: '应收股利', type: 'asset' },
  { code: '1132', name: '应收利息', type: 'asset' },
  { code: '1221', name: '其他应收款', type: 'asset' },
  { code: '1401', name: '材料采购', type: 'asset' },
  { code: '1402', name: '在途物资', type: 'asset' },
  { code: '1403', name: '原材料', type: 'asset' },
  { code: '1404', name: '材料成本差异', type: 'asset' },
  { code: '1405', name: '库存商品', type: 'asset' },
  { code: '1407', name: '商品进销差价', type: 'asset' },
  { code: '1408', name: '委托加工物资', type: 'asset' },
  { code: '1411', name: '周转材料', type: 'asset' },
  { code: '1471', name: '存货跌价准备', type: 'asset' },
  { code: '1501', name: '持有至到期投资', type: 'asset' },
  { code: '1502', name: '持有至到期投资减值准备', type: 'asset' },
  { code: '1503', name: '可供出售金融资产', type: 'asset' },
  { code: '1511', name: '长期股权投资', type: 'asset' },
  { code: '1512', name: '长期股权投资减值准备', type: 'asset' },
  { code: '1521', name: '投资性房地产', type: 'asset' },
  { code: '1531', name: '长期应收款', type: 'asset' },
  { code: '1532', name: '未实现融资收益', type: 'asset' },
  { code: '1601', name: '固定资产', type: 'asset' },
  { code: '1602', name: '累计折旧', type: 'asset' },
  { code: '1603', name: '固定资产减值准备', type: 'asset' },
  { code: '1604', name: '在建工程', type: 'asset' },
  { code: '1605', name: '工程物资', type: 'asset' },
  { code: '1606', name: '固定资产清理', type: 'asset' },
  { code: '1611', name: '未担保余值', type: 'asset' },
  { code: '1621', name: '生产性生物资产', type: 'asset' },
  { code: '1622', name: '生产性生物资产累计折旧', type: 'asset' },
  { code: '1623', name: '公益性生物资产', type: 'asset' },
  { code: '1631', name: '油气资产', type: 'asset' },
  { code: '1632', name: '累计折耗', type: 'asset' },
  { code: '1701', name: '无形资产', type: 'asset' },
  { code: '1702', name: '累计摊销', type: 'asset' },
  { code: '1703', name: '无形资产减值准备', type: 'asset' },
  { code: '1711', name: '商誉', type: 'asset' },
  { code: '1801', name: '长期待摊费用', type: 'asset' },
  { code: '1811', name: '递延所得税资产', type: 'asset' },
  { code: '1821', name: '独立账户资产', type: 'asset' },
  { code: '1901', name: '待处理财产损溢', type: 'asset' },
  { code: '2001', name: '短期借款', type: 'liability' },
  { code: '2101', name: '交易性金融负债', type: 'liability' },
  { code: '2201', name: '应付票据', type: 'liability' },
  { code: '2202', name: '应付账款', type: 'liability' },
  { code: '2203', name: '预收账款', type: 'liability' },
  { code: '2211', name: '应付职工薪酬', type: 'liability' },
  { code: '2221', name: '应交税费', type: 'liability' },
  { code: '2231', name: '应付利息', type: 'liability' },
  { code: '2232', name: '应付股利', type: 'liability' },
  { code: '2241', name: '其他应付款', type: 'liability' },
  { code: '2314', name: '代理业务负债', type: 'liability' },
  { code: '2401', name: '递延收益', type: 'liability' },
  { code: '2501', name: '长期借款', type: 'liability' },
  { code: '2502', name: '应付债券', type: 'liability' },
  { code: '2601', name: '未到期责任准备金', type: 'liability' },
  { code: '2602', name: '保险责任准备金', type: 'liability' },
  { code: '2611', name: '保户储金', type: 'liability' },
  { code: '2621', name: '独立账户负债', type: 'liability' },
  { code: '2701', name: '长期应付款', type: 'liability' },
  { code: '2702', name: '未确认融资费用', type: 'liability' },
  { code: '2711', name: '专项应付款', type: 'liability' },
  { code: '2801', name: '预计负债', type: 'liability' },
  { code: '2901', name: '递延所得税负债', type: 'liability' },
  { code: '3001', name: '清算资金往来', type: 'liability' },
  { code: '3002', name: '货币兑换', type: 'liability' },
  { code: '3101', name: '衍生工具', type: 'liability' },
  { code: '3201', name: '套期工具', type: 'liability' },
  { code: '3202', name: '被套期项目', type: 'liability' },
  { code: '4001', name: '实收资本', type: 'equity' },
  { code: '4002', name: '资本公积', type: 'equity' },
  { code: '4101', name: '盈余公积', type: 'equity' },
  { code: '4103', name: '本年利润', type: 'equity' },
  { code: '4104', name: '利润分配', type: 'equity' },
  { code: '4201', name: '库存股', type: 'equity' },
  { code: '5001', name: '制造费用', type: 'cost' },
  { code: '5101', name: '生产成本', type: 'cost' },
  { code: '5201', name: '劳务成本', type: 'cost' },
  { code: '5301', name: '研发支出', type: 'cost' },
  { code: '5401', name: '工程施工', type: 'cost' },
  { code: '5402', name: '工程结算', type: 'cost' },
  { code: '5403', name: '机械作业', type: 'cost' },
  { code: '6001', name: '主营业务收入', type: 'revenue' },
  { code: '6051', name: '其他业务收入', type: 'revenue' },
  { code: '6101', name: '公允价值变动损益', type: 'revenue' },
  { code: '6111', name: '投资收益', type: 'revenue' },
  { code: '6301', name: '营业外收入', type: 'revenue' },
  { code: '6401', name: '主营业务成本', type: 'expense' },
  { code: '6402', name: '其他业务成本', type: 'expense' },
  { code: '6403', name: '营业税金及附加', type: 'expense' },
  { code: '6601', name: '销售费用', type: 'expense' },
  { code: '6602', name: '管理费用', type: 'expense' },
  { code: '6603', name: '财务费用', type: 'expense' },
  { code: '6701', name: '资产减值损失', type: 'expense' },
  { code: '6711', name: '营业外支出', type: 'expense' },
  { code: '6801', name: '所得税费用', type: 'expense' },
  { code: '6901', name: '以前年度损益调整', type: 'expense' }
])

// 表单验证规则
const entryRules = {
  accountCode: [{ required: true, message: '请选择科目', trigger: 'change' }],
  debitAmount: [{ required: true, message: '请输入借方金额', trigger: 'blur' }],
  creditAmount: [{ required: true, message: '请输入贷方金额', trigger: 'blur' }],
  summary: [{ required: true, message: '请输入摘要', trigger: 'blur' }]
}

// 借贷平衡检查
const balanceStatus = computed(() => {
  const totalDebit = entries.value.reduce((sum, entry) => sum + (entry.debitAmount || 0), 0)
  const totalCredit = entries.value.reduce((sum, entry) => sum + (entry.creditAmount || 0), 0)
  const difference = Math.abs(totalDebit - totalCredit)
  
  if (difference === 0) {
    return {
      type: 'success',
      title: '借贷平衡',
      description: `借方合计：¥${totalDebit.toLocaleString()}，贷方合计：¥${totalCredit.toLocaleString()}`
    }
  } else {
    return {
      type: 'error',
      title: '借贷不平衡',
      description: `借方合计：¥${totalDebit.toLocaleString()}，贷方合计：¥${totalCredit.toLocaleString()}，差额：¥${difference.toLocaleString()}`
    }
  }
})

// 方法
function addEntry() {
  entryDialog.isEdit = false
  Object.assign(entryDialog.form, {
    id: '',
    accountCode: '',
    accountName: '',
    debitAmount: 0,
    creditAmount: 0,
    summary: '',
    auxiliary: '',
    auxiliaryValue: ''
  })
  entryDialog.visible = true
}

function editEntry(entry: any) {
  entryDialog.isEdit = true
  Object.assign(entryDialog.form, { ...entry })
  entryDialog.visible = true
}

function deleteEntry(entry: any) {
  ElMessageBox.confirm(
    `确定要删除该分录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = entries.value.findIndex(e => e.id === entry.id)
    if (index > -1) {
      entries.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

function closeEntryDialog() {
  entryDialog.visible = false
  entryFormRef.value?.resetFields()
}

function saveEntry() {
  entryFormRef.value?.validate((valid) => {
    if (valid) {
      if (entryDialog.isEdit) {
        // 编辑
        const index = entries.value.findIndex(e => e.id === entryDialog.form.id)
        if (index > -1) {
          entries.value[index] = { ...entryDialog.form }
        }
      } else {
        // 新增
        const newEntry = {
          ...entryDialog.form,
          id: Date.now()
        }
        entries.value.push(newEntry)
      }
      
      ElMessage.success('保存成功')
      closeEntryDialog()
    }
  })
}

function onAccountChange(accountCode: string) {
  const account = accountSubjects.value.find(a => a.code === accountCode)
  if (account) {
    entryDialog.form.accountName = account.name
  }
}

function autoGenerateEntries() {
  // 根据凭证类型自动生成标准会计分录
  ElMessage.info('自动生成功能开发中...')
}

// 监听借贷金额变化，确保借贷平衡
watch(() => entryDialog.form.debitAmount, (newVal) => {
  if (newVal > 0) {
    entryDialog.form.creditAmount = 0
  }
})

watch(() => entryDialog.form.creditAmount, (newVal) => {
  if (newVal > 0) {
    entryDialog.form.debitAmount = 0
  }
})
</script>

<style scoped>
.accounting-entry {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.debit-amount {
  color: #e6a23c;
  font-weight: 500;
}

.credit-amount {
  color: #67c23a;
  font-weight: 500;
}

.balance-check {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
